
layui.use(['form', 'layer', 'laydate', 'table', 'upload'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var get_product_url = $('.get_product_url').val();
    var get_productlist_url = $('.get_productlist_url').val();
    var handle_url = $('.handle_url').val();

    laydate.render({
        elem: '#test16'
        ,type: 'datetime'
        ,range: '到'
        ,format: 'yyyy年M月d日H时m分s秒'
    });


    //优惠券开始日期
    laydate.render({
        elem: '#start_time'
    });
    //优惠券结束日期
    laydate.render({
        elem: '#end_time'
    });


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 20,
        limits : [10, 20, 50, 100],
        id : "dataTable",
        cols : [[
            /* {type: "checkbox", fixed:"left", width:50},*/
            {field: 'name', title: '拼团商品',align:'center', minWidth:240},
            {field: 'price', title: '原价', align:'center',templet:function(d){
                return formatMoney(d.price/100,1)
            }},
            {field: 'group_price', title: '团购价', align:'center',templet:function(d){
                return formatMoney(d.group_price/100,1)
            }},
            {field: 'group_succ_count', title: '成团人数', align:"center"},
            {field: 'group_succ_time', title: '组团时限', align:'center',templet:function(d){
                return d.group_succ_time/3600 + '小时'
            }},
            {field: 'end_time', title: '活动时间',width:300, align:'center',templet:function(d){
                return d.start_time + '~~' + d.end_time
            }},
            // {field: 'status', title: '面向用户', align:'center'},
            {field: 'p_status', title: '活动状态', align:'center'},
            {field: 'status', title: '禁用与启用', align:"center", templet:function(data){
                var html = '';
                if (data.status == 1) {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'" checked>';
                } else {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'">';
                }

                return html;
            }},
            {field: 'create_date', title: '创建时间',width:200, align:'center', sort: true},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){
        if ($('.name').val() != ''){
            var name = $('.searchBox').find('input[name=name]').val();
        }
        if ($('.p_status').val() != '') {
            var p_status = $('.p_status').val();
        }

        table.reload("dataTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                name: name,
                p_status: p_status,
            }
        });
    });

    form.on('switch(status)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});

        var status = 2;
        if(data.elem.checked){
            status = 1;
        }

        $.ajax({
            url: handle_url,
            data: {'id' : data.elem.value,'status' : status},
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    });

    // 批量删除
    $(".delAll_btn").on("click", function(){
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"ids": ids},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功', {icon: 1});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的数据");
        }
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });


    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){

            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){
        var content = add_url;

        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2,
            anim: 1,
            title: false,
            closeBtn: false,
            offset: 'r',
            shade: 0.2,
            //, shadeClose: true // 是否点击遮罩关闭
            skin: 'layui-anim layui-anim-rl layui-layer-adminRight',
            area: '680px',
            top: 0,
            content: content
        });
    }

    // Table 列表
    var sessionProduct = table.render({
        elem: '#dataTable01',
        url : get_productlist_url,
        page : false,
        cellMinWidth : 95,
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "table01List",
        initSort: {
            field: 'create_date' // 排序字段，对应 cols 设定的各字段名
            ,type: 'desc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        cols : [[
            {field: "name", title:"商品名称",align:'center',minWidth:140},
            {field: 'bar_code', title: '条码',align:'center', minWidth:180},
            {field: 'typeName', title: '分类', align:'center'},
            {field: 'store_count', title: '库存',align:'center'},
            {field: 'price', title: '销售价',align:'center', minWidth:80,templet:function(d){
                return formatMoney(d.price/100,1)
            }},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<button type="button" class="layui-btn" style="height: 28px;line-height: 28px;" lay-event="purchase-add">选取 <input type="text" style="display:none" value="' +
                    ''+data.id+'" name="product_id"></button>'  ;
                return html;
            }}
        ]]
    });
    // 搜索
    $(".search01_btn").on("click", function(){
        if($('.name').val() != ''){
            table.reload("table01List", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: $('.searchBox').find('.name').val()  //搜索的关键字
                }
            });
        }else{
            layer.msg("请输入搜索的内容");
        }
    });
    // 清空搜索
    $(".reset01_btn").on("click", function(){
        table.reload("table01List", {
            where: {
                name: '',
            }
        });
    });

    // 列表操作
    table.on('tool(dataTable01)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        // 选取
        var price = formatMoney(data.price/100,1)
        if (layEvent == 'purchase-add') {
            layer.msg('选择成功', {icon: 1, time: 1000});
            var index = parent.layer.getFrameIndex(window.name);
            $(parent.window.frames[0].document).find('#product_id').val(data.id)
            $(parent.window.frames[0].document).find('#product_name').text(data.name + '（售价：¥'+price + '）')
            layer.close(index);
        }
    });


    //选择优惠商品
    $('.product').on('click', function(){
        top.layer.open({
            type: 2,
            anim: 1,
            title: '选择商品',
            shade: 0.2,
            skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe',
            area: ['900px','700px'],
            content: get_product_url,
            yes:function () {
                sessionProduct.reload();
            }

        });
    });

    //是否最低消费
    $('.layui-form-switch').on('click',function(){
        if ($('.min_consumption').hasClass('layui-hide')){
            $('.min_consumption').removeClass('layui-hide')
        }else{
            $('input[name="min_consumption"]').val('');
            $('.min_consumption').addClass('layui-hide');

        }
    });

    // 自定义验证规则
    form.verify({
        product_id: function(value){
            if(value.trim() == ''){
                return '请选择商品';
            }
        },
        group_price:function (value) {
            if(value.trim() == ''){
                return '请填写团购价格';
            }
            if(value <= 0){
                return '请输入正确的价格'
            }
            if(!/^[0-9]+(.[0-9]{1,2})?$/.test(value)){
                return '请输入正确的价格'
            }

        },
        group_succ_count:function (value) {
            if(value.trim() == ''){
                return '请输入成团人数';
            }
            if(!(/(^[1-9]\d*$)/.test(value)) || value < 2){
                return '成团人数必须大于1且是整数'
            }
        },
        confine_count:function (value) {
            if(value.trim() != ''){
                if(!/^\+?[1-9]\d*$/.test(value)){
                    return '限购数量不合法'
                }
            }
        },

        group_succ_time:function (value) {
            if(!/^[0-9]+([.]{1}[0-9]{1})?$/.test(value) || value <= 0){
                return '拼团时限不合法'
            }
        },

        start_time:function (value) {
            if(value.trim() == ''){
                return '活动开始时间必填'
            }
        },
        end_time:function (value) {
            if(value.trim() == ''){
                return '活动结束时间必填'
            }
        },
    });

    // 表单提交
    form.on("submit(laySave)", function(data){
        //弹出loading
        if(data.field.start_time >= (data.field.end_time + ' 23:59:59')){
            layer.msg('开始时间不能大于结束时间');
            return false;
        }
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                if(res.code == 1){
                    // var index = parent.layer.getFrameIndex(window.name);
                    // // 关闭当前frame
                    // parent.layer.close(index);

                    layer.closeAll("iframe");
                    //parent.window.tableIns.reload();
                    parent.layui.table.reload('tableList', {});
                    // 刷新父页面
                    parent.location.reload();
                }else {
                    layer.msg(res.msg);
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });

    })
});